package com.cgs.mongo.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
import org.bson.BsonDocument;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class WrapperUtils {

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    public static BsonDocument asBsonDocument(Map<String, Object> filter) throws JsonProcessingException {
        return BsonDocument.parse(OBJECT_MAPPER.writeValueAsString(filter));
    }

    public static List<BsonDocument> asBsonDocuments(List<Map<String, Object>> filters) throws JsonProcessingException {
        List<BsonDocument> documents = new ArrayList<>(filters.size());
        for (Map<String, Object> p : filters) {
            documents.add(asBsonDocument(p));
        }
        return documents;
    }

    public static <T> T populate(T t, Map<String, Object> properties) throws InvocationTargetException, IllegalAccessException {
        BeanUtils.populate(t, properties);
        return t;
    }

    public static boolean getBoolean(Map<String, Object> properties, String key, boolean defaultValue) {
        return Boolean.valueOf(properties.getOrDefault(key, defaultValue).toString());
    }

}
